package com.jiangong.Crawler;

import com.jiangong.entity.WeatherAPI;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
@Component
public class WeatherCrawler{
    static String URL="https://api.msn.cn/weather/overview?apikey=j5i4gDqHL6nGYwx5wi5kRhXjtf2c5qgFX9fzfk0TOo&activityId=97FF7582-EC6A-4CA0-92B0-BC4C69858654&ocid=msftweather&cm=zh-cn&it=edgeid&user=m-15AC45027C7C66A916A057677D1A6754&scn=APP_ANON&units=C&appId=9e21380c-ff19-4c78-b4ea-19558e93a5d3&wrapodata=false&includemapsmetadata=true&cuthour=true&lifeDays=2&lifeModes=18&includestorm=true&includeLifeActivity=true&lifeSubTypes=1%2C3%2C4%2C10%2C26&insights=65536&startDate=-1&endDate=%2B9&discardFutureInsightTimeseries=true&distanceinkm=0&regionDataCount=20&orderby=distance&days=10&pageOcid=prime-weather%3A%3Aweathertoday-peregrine&source=weather_csr&fdhead=PRG-1SW-WXWPDEL%2CPRG-1SW-WXWPDS%2CPRG-1SW-WXWPTLI&region=cn&market=zh-cn&locale=zh-cn&lat=38.874&lon=115.4646";
    //主函数入口

    public static WeatherAPI getWeather() throws IOException {
        //建立一个新的请求客户端
        CloseableHttpClient httpClient= HttpClients.createDefault();

        //使用HttpGet的方式请求网址
        HttpGet httpGet = new HttpGet(URL);

        //获取网址的返回结果
        CloseableHttpResponse response=null;
        try {
            response=httpClient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取返回结果中的实体
        HttpEntity entity = response.getEntity();
                //将返回的实体输出
        String str = EntityUtils.toString(entity);
        JSONObject jsonObject = new JSONObject(str);
        JSONObject resultObj = jsonObject.getJSONArray("responses").getJSONObject(0).getJSONArray("weather").getJSONObject(0).getJSONObject("current");


        try {
            // 气压 (handle potential null and type conversion)
            BigDecimal baroDecimal = resultObj.optBigDecimal("baro", BigDecimal.ZERO);
            double mpa = baroDecimal.doubleValue();  // Note: Changed variable name to lowercase as per Java conventions

            // 湿度 (handle NumberFormatException)
            double humidity = resultObj.has("rh") ?
                    Double.parseDouble(resultObj.optString("rh", "0")) : 0;

            // 温度
            double temperature = resultObj.has("temp") ?
                    Double.parseDouble(resultObj.optString("temp", "0")) : 0;

            // 天气情况 (handle potential null)
            String weather = resultObj.optString("cap", "");

            // 空气质量
            double quality = resultObj.has("aqi") ?
                    Double.parseDouble(resultObj.optString("aqi", "0")) : 0;

            // 风速
            String wind = resultObj.optString("pvdrWindSpd", "");

            // 风向
            String windDirection = resultObj.optString("pvdrWindDir", "");

            // 露点
            double dewPoint = resultObj.has("dewPt") ?
                    Double.parseDouble(resultObj.optString("dewPt", "0")) : 0;

            // 体感温度
            double feelsLike = resultObj.has("feels") ?
                    Double.parseDouble(resultObj.optString("feels", "0")) : 0;

            // 空气质量图片
            String qualityImg = resultObj.optString("urlIcon", "");

            // 检测时间 (handle DateTimeParseException)
            LocalDateTime createTime = null;
            if (jsonObject.has("created")) {
                try {
                    createTime = LocalDateTime.parse(jsonObject.optString("created", ""));
                } catch (DateTimeParseException e) {
                    // Handle parse error or set default
                    createTime = LocalDateTime.now();
                }
            } else {
                createTime = LocalDateTime.now();
            }

            WeatherAPI weatherAPI = new WeatherAPI(mpa, humidity, temperature, weather, quality, wind, dewPoint, feelsLike, qualityImg, createTime);
            System.out.println(weatherAPI);
            return weatherAPI;

        } catch (NumberFormatException e) {
            // Handle number parsing errors
            e.printStackTrace();
        } catch (Exception e) {
            // Handle other unexpected errors
            e.printStackTrace();
        }
        return null;
    }
}
